package com.yanqu.road.server.cmd.grandchild.exam;

import com.yanqu.road.pb.grandchild.GrandChildProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.config.grandchild.GrandChildMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = GameProtocol.S_GRAND_CHILD_SYNC_EXAM_FINISH_FROM_CROSS, desc = "科举结果加奖励")
public class SyncImperialExamResultFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        GrandChildProto.CrossSyncExamFinishMsg reqMsg = GrandChildProto.CrossSyncExamFinishMsg.parseFrom(packet.getBytes());

        // 处理科举结果
        GrandChildMgr.handleExamResult(reqMsg);

        // 返回跨服
        GrandChildProto.CrossSetExamHandleStatusReqMsg.Builder tmp = GrandChildProto.CrossSetExamHandleStatusReqMsg.newBuilder();
        tmp.setExamNo(Long.valueOf(reqMsg.getNo()));
        YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_GRAND_CHILD_SET_EXAM_HANDLE_STATUS, tmp);
        GamePlayerMgr.sendPacket(0, message);

        // 同步给在线玩家
        for (GamePlayer onlinePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            GrandChildProto.SyncExamFinishMsg.Builder builder = GrandChildProto.SyncExamFinishMsg.newBuilder();
            builder.setNo(reqMsg.getNo());
            builder.setJoin(false);
            for (GrandChildProto.ExamPupilResultMsg msg : reqMsg.getResultList()) {
                if (msg.getUserId() == onlinePlayer.getUserId()) {
                    builder.setJoin(true);
                    break;
                }
            }
            onlinePlayer.sendPacket(ClientProtocol.U_GRAND_CHILD_SYNC_FINISH, builder);
        }
    }

}
